import { Modal } from 'antd'
import { SetStateAction, useMemo, useState } from 'react'
import { getItem, message, reTokenAndUpdateInfo, USERRESULT } from '@hs-admin/utils'
import { HsAdminInput } from '@hs-admin/base-components'
import { change_email } from '@/api/common'
import { getUserInfo, refreshToken } from '@/api/login.ts'

export const useChangeEmail = () => {
  const [open, setOpen] = useState(false)

  const [email, setEmail] = useState('')

  const [inputEmail, setInputEmail] = useState('')

  return useMemo(
    () => ({
      EmailModal: (
        <Modal
          open={open}
          width="50vw"
          onCancel={() => {
            setOpen(false)
          }}
          onOk={() => {
            if (!inputEmail) {
              message.error('请输入邮箱')
              return
            }
            change_email({
              email: `${inputEmail}`
            }).then(() => {
              reTokenAndUpdateInfo(refreshToken, getUserInfo).then(() => {
                setEmail(getItem(USERRESULT)?.email ?? '')
                message.success('修改成功')
                setOpen(false)
              })
            })
          }}>
          <div>
            <div className="flex flex-col gap-4">
              <h2>当前邮箱：{email}</h2>
              <div className="flex gap-4 items-center">
                <span className="whitespace-nowrap">设置个人邮箱：</span>
                <HsAdminInput
                  value={inputEmail}
                  onChange={(e: { target: { value: SetStateAction<string> } }) => {
                    setInputEmail(e.target.value)
                  }}
                />
              </div>
            </div>
          </div>
        </Modal>
      ),
      doOpen: () => {
        setEmail(getItem(USERRESULT)?.email ?? '')
        setInputEmail('')
        setOpen(true)
      }
    }),
    [email, inputEmail, open]
  )
}
